<template>
    <div class="baseInfo-page hp100">
        <Tabs :value="currentTab" v-if="showTabList.length > 1" @on-click="changeTab">
            <TabPane v-for="tab in showTabList" :key="tab.name" :label="tab.label" :name="tab.name">
                <ItemUpload
                    v-if="false"
                    :ref="`fileUpload${tab.name}`"
                    showUploadList
                    :showChooseBtn="false"
                    @upload-success="
                        (data) => {
                            bindResource(data, tab.name);
                        }
                    "
                    @del-item="delResourceBind"
                    :fileType="tab.fileType"
                    :download="true"
                    showType="table"
                    :fileList="getFileList(tab.name)"
                    :formatArr="tab.formatArr"
                >
                    <template #list>
                        <TableList
                            :columns="fileColumns"
                            :data="getFileList(tab.name)"
                            class="mt10"
                        ></TableList>
                    </template>
                    <template #search>
                        <Input
                            v-model="relationQueryInfo.fileName"
                            @on-change="debounceQuery"
                            placeholder="请输入名称"
                            style="width: 180px; margin-left: 10px;"
                        ></Input>
                    </template>
                </ItemUpload>
                <!-- <Page
                                :total="getFileList(tab.name).length"
                                :current="queryFileInfo.pageIndex"
                                :page-size="queryFileInfo.pageSize"
                                :show-total="true"
                                @on-change="changeFilePage"
                                style="margin: 20px 0px;text-align:center;"
                            /> -->
            </TabPane>
        </Tabs>
        <SearchTable 
            :columns="getShowColumns()"
            :data="contentList"
            :total="contentTotal"
            :loading="loading"
            :page.sync="queryFileInfo.pageIndex"
            :size.sync="queryFileInfo.pageSize"
            @queryFun="getResourceBind"
            class="hp100"
            >
            <slot slot="search">
                <Button icon="ios-cloud-upload-outline" @click="openUploadModal()" v-if="isRootDesigner">上传文件</Button>
                <Input
                    v-model="relationQueryInfo.fileName"
                    @on-change="debounceQuery"
                    placeholder="请输入名称"
                    clearable
                    style="width: 180px; margin-right: 10px"
                ></Input>
            </slot>
        </SearchTable>
        <div class="list-wrapper" v-if="false">
            <div class="flex-between">
                <div class="flex">
                    <Button icon="ios-cloud-upload-outline" @click="openUploadModal()" v-if="isRootDesigner" style="margin-left: 10px">上传文件</Button>
                
                    <!-- <Select filterable
                        v-if="currentTab == 'document'"
                        v-model="relationQueryInfo.typeCode"
                        @on-change="getResourceBind()"
                        placeholder="请选择文档类型"
                        clearable
                        style="width: 150px; margin-left: 10px"
                    >
                        <Option v-for="type in categoryList" :value="type.id" :key="type.category">{{
                            type.category
                        }}</Option>
                    </Select> -->
                    <Input
                        v-model="relationQueryInfo.fileName"
                        @on-change="debounceQuery"
                        placeholder="请输入名称"
                        clearable
                        style="width: 180px; margin-right: 10px"
                    ></Input>
                </div>
                <!-- <Category v-if="isRootDesigner"></Category> -->
            </div>
            <TableList
                :columns="getShowColumns()"
                :data="getFileList(currentTab)"
                :loading="loading"
                class="mt10 cardList"
            ></TableList>
        </div>
        <Modal
            v-model="uploadModal.show"
            title="上传文件"
            :loading="uploadModal.loading"
            @on-ok="bindDocs"
        >
            <Form
                ref="uploadFormValidate"
                :model="uploadFormValidate"
                :rules="uploadRuleValidate"
                :label-width="60"
            >
                <!-- <FormItem label="类型" prop="docType" v-if="currentTab === 'document'">
                    <RadioGroup v-model="uploadFormValidate.docType">
                        <Radio :label="type.value" :key="type.value" v-for="type in docTypeList">{{
                            type.label
                        }}</Radio>
                    </RadioGroup>
                </FormItem> -->
                <!-- <FormItem label="类型" prop="typeCode" v-if="currentTab === 'document'">
                    <Select filterable v-model="uploadFormValidate.typeCode" placeholder="请选择类型">
                        <Option v-for="type in categoryList" :value="type.id" :key="type.category">{{
                            type.category
                        }}</Option>
                    </Select>
                </FormItem> -->
                <FormItem label="文件" prop="fileId">
                    <ItemUpload
                        v-if="uploadModal.show"
                        :ref="`fileUpload`"
                        :fileId.sync="uploadFormValidate.fileId"
                        :filePath.sync = "uploadFormValidate.filePath"
                        :fileName.sync = "uploadFormValidate.fileName"
                        :uploadLoading.sync="isUploading"
                        :type="tabList[currentTab].fileType"
                        :format="tabList[currentTab].formatArr"
                        @upload-success="getUploadInfo"
                    >
                    </ItemUpload>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>
<script>
import ItemUpload from '@/components/item-upload/single.vue';
// import cardList from '@/components/list-template/card-list/cardList.vue';
import {
    queryContentRelation,
    addContentRelation,
    delContentRelation,
} from '../api/contentRelation.js';
import Category from '../category'
import { queryAllCategory } from '../api/category.js'
import { mapState } from 'vuex'
import { debounce } from '@/libs/utils';
export default {
    name: 'DocInfo',
    components: {
        ItemUpload,
        Category
    },
    inject: ['detailParent'],
    props: {
        showType: {
            type: String,
            default: '1', //1、显示文档和视频 2、显示程序和工具 3、参考资料
        },
    },
    data() {
        return {
            // type  file
            loading: false,
            currentTab: this.showType === '3' ? 'document' : this.showType === '1' ? 'video' : 'programs',
            tabList: {
                // tool: {
                //     type: 1,
                //     showType:2
                // },
                video: {
                    type: 3,
                    showType: ['1'],
                    label: '视频',
                    name: 'video',
                    fileType: 'videos',
                    formatArr: [
                        'mp4',
                        'webm',
                        'ogv',
                        'ogg',
                        '3gp',
                        '3g2',
                        'm4v',
                        'mpg',
                        'vob',
                        'fli',
                        'mkv',
                        'asf',
                        'asx',
                        'wmv',
                        'flv',
                        'avi',
                    ],
                },
                document: {
                    type: 2,
                    showType: ['1','3'],
                    label: '文档',
                    name: 'document',
                    fileType: 'docs',
                    formatArr: [
                        'pdf',
                        'doc',
                        'docx',
                        'xls',
                        'xlsx',
                        'xla',
                        'pptx',
                        'pps',
                        'ppt',
                        'rtf',
                        'txt',
                        'md',
                    ],
                },
                programs: {
                    type: 4,
                    showType: ['1'],
                    label: '程序',
                    name: 'programs',
                    fileType: 'files',
                    formatArr: ['zip'],
                },
            },
            relationQueryInfo: {
                fileName: '',
                docType: '',
            },
            docTypeList: [
                {
                    label: '设计方案 ',
                    value: 1,
                },
                {
                    label: '课件数据',
                    value: 2,
                },
                {
                    label: '总结报告',
                    value: 3,
                }
            ],
            uploadModal: {
                show: false,
                title: '上传视频',
                loading: true,
            },
            uploadFormValidate: {
                docType: 1,
                fileId: '',
                filePath: '',
                fileName: '',
                typeCode:''
            },
            uploadRuleValidate: {
                docType: [
                    {
                        type: 'number',
                        required: true,
                        trigger: 'change',
                        message: '请选择文件类型',
                    }
                ],
                typeCode: [
                    {
                        required: true,
                        trigger: 'change',
                        message: '请选择文件类型',
                    }
                ],
                fileId: [
                    {
                        type: 'string',
                        required: true,
                        trigger: 'change',
                        message: '请上传文件',
                    },
                ],
                filePath: [
                    {
                        type: 'string',
                        required: true,
                        trigger: 'change',
                    },
                ],
                fileName: [
                    {
                        type: 'string',
                        required: true,
                        trigger: 'change',
                    },
                ],
            },
            resource: {
                tool: 1,
                document: 2,
                video: 3,
                programs: 4,
            },
            allContentRelation: [],
            queryFileInfo: {
                pageIndex: 1,
                pageSize: 10,
            },
            contentList:[],
            contentTotal:0,
            isUploading:false,
            fileColumns: [
                {
                    title: '名称',
                    key: 'fileName',
                    align: 'center',
                    tooltip: true,
                    width: 200,
                    placement: 'top-left',
                },
                {
                    title: '上传时间',
                    key: 'createTime',
                    align: 'center',
                    tooltip: true,
                },
                // {
                //     title: '文档类型',
                //     key: 'docType',
                //     align: 'center',
                //     tooltip: true,
                //     show: () => {
                //         return this.currentTab === 'document';
                //     },
                //     render: (h, params) => {
                //         let { docType } = params.row;
                //         return h(
                //             'span',
                //             docType === 1
                //                 ? '设计方案'
                //                 : docType === 2
                //                 ? '课件数据'
                //                 : docType === 3
                //                 ? '总结报告'
                //                 : ''
                //         );
                //     },
                // },
                {
                    title: '操作',
                    key: 'action',
                    width: 180,
                    key:'action',
                    placement: 'top-right',
                    opList:[
                        {
                            txt:'下载',
                            fun:this.download
                        },
                        {
                            txt:'预览',
                            fun:this.checkInfo
                        },
                        {
                            txt:'删除',
                            type:'delete',
                            tooltip:true,
                            title: '您确定要删除吗？',
                            show:() => {
                                return this.isRootDesigner
                            },
                            disabled:() => this.disabledAllBtn,
                            fun:(data) => this.delResourceBind(data.id)
                        }
                    ]
                },
            ],
            categoryList:[]
        };
    },
    computed: {
        documentList() {
            return this.allContentRelation.filter((item) => item.type === 2);
        },
        videoList() {
            return this.allContentRelation.filter((item) => item.type === 3);
        },
        toolList() {
            return this.allContentRelation.filter((item) => item.type === 1);
        },
        programsList() {
            return this.allContentRelation.filter((item) => item.type === 4);
        },
        showTabList() {
            return Object.values(this.tabList).filter((tab) => tab.showType.includes(this.showType));
        },
        pageFileList() {
            return this.getFileList(this.currentTab).slice(
                (this.queryFileInfo.pageIndex - 1) * this.queryFileInfo.pageSize,
                this.queryFileInfo.pageIndex * this.queryFileInfo.pageSize
            );
        },
        disModifyTemplate() {
            return ![0, 10].includes(this.contentDetail.deployStatus);
        },
        contentDetail() {
            return this.detailParent.contentDetail;
        },
        contentId() {
            return this.contentDetail.id;
        },
        disabledAllBtn(){
            return this.detailParent.disabledAllBtn
        },
        ...mapState('user', {
          'USER_ID':state => state.userId,
          'isRootDesigner':state => state.isRootDesigner
        }),
    },
    watch: {
        contentDetail: {
            handler(val, oldVal) {
                if (val.id != oldVal.id) {
                    this.getResourceBind();
                }
            },
        },
    },
    created() {},
    mounted() {
        let { id } = this.contentDetail;
        if (!id) {
            return;
        }
        this.getResourceBind();
        this.queryCategory();
    },
    methods: {
        queryCategory(){
            queryAllCategory().then(({code,data,message}) => {
                if(code === 1){
                    this.categoryList = data;
                }else{

                }
            }).catch(error => {

            })
        },
        getShowColumns() {
            return this.fileColumns.filter((col) => {
                return typeof col.show === 'function'
                    ? col.show()
                    : col.show !== false
                    ? true
                    : false;
            });
        },
        changeTab(name) {
            this.currentTab = name;
        },
        getFileList(type) {
            return this[`${type}List`];
        },
        changeFilePage(page) {
            this.queryFileInfo.pageIndex = page;
        },
        getUploadInfo(data) {
            this.uploadFormValidate = { ...this.uploadFormValidate, ...data };
        },
        bindDocs() {
            if (this.isUploading) {
                this.$Message.info('请等待文件上传成功');
                this.uploadModal.loading = false;
                setTimeout(() => {
                    this.uploadModal.loading = true;
                });
                return;
            }
            this.$refs.uploadFormValidate.validate((valid) => {
                if (valid) {
                    this.bindResource(this.uploadFormValidate, this.tabList[this.currentTab].name);
                } else {
                    this.uploadModal.loading = false;
                    setTimeout(() => {
                        this.uploadModal.loading = true;
                    });
                }
            });
        },
        // 添加绑定文档，视频，工具
        bindResource(data, type) {
            let { fileId, filePath, fileName } = data;
            let params = {
                contentId: this.contentDetail.id,
                fileId,
                fileName,
                path: filePath,
                type: this.resource[type],
            };
            if (type === 'document') {
                params.docType = data.docType;
                params.typeCode = data.typeCode;
            }
            addContentRelation(params)
                .then(({ code, data: reId, message }) => {
                    if (code === 1) {
                        this.$Message.info('添加成功');
                        this.uploadModal.show = false;
                        this.getResourceBind();
                        // this.allContentRelation.push({ ...params, id: reId });
                    } else {
                        this.$Message.error(message);
                    }
                })
                .catch((error) => {})
                .finally(() => {
                    this.uploadModal.loading = false;
                    setTimeout(() => {
                        this.uploadModal.loading = true;
                    });
                });
        },
        openUploadModal() {
            this.uploadFormValidate = {
                docType: 1,
                fileId: '',
                fileType: '',
                fileName: '',
                typeCode:''
            };
            this.$refs.uploadFormValidate.resetFields();
            this.uploadModal.show = true;
        },
        // 删除绑定文档，视频，工具
        delResourceBind(id) {
            delContentRelation(id)
                .then(({ code, message }) => {
                    if (code === 1) {
                        this.$Message.info('删除成功');
                        this.allContentRelation.splice(
                            this.allContentRelation.findIndex((item) => item.id === id),
                            1
                        );
                    } else {
                        this.$Message.error(message);
                    }
                })
                .catch((error) => {});
        },
        debounceQuery: debounce(function () {
            this.getResourceBind();
        }, 500),
        //查询绑定
        getResourceBind() {
            this.loading = true;
            let params = {
                contentId: this.contentDetail.id,
                // pageIndex: 1,
                ...this.queryFileInfo,
                // pageSize: 1000000,
            };

            let { fileName, docType } = this.relationQueryInfo;
            fileName && (params.fileName = fileName);
            docType && (params.docType = docType);
            queryContentRelation(params)
                .then(({ code, data: { items,total }, message }) => {
                    if (code === 1) {
                        // this.allContentRelation = items;
                        this.contentList = items;
                        this.contentTotal = total;
                    } else {
                        this.$Message.error(message);
                    }
                })
                .catch((error) => {}).finally(() => {
                    this.loading = false;
                });
        },
        checkInfo(data) {
            let path = data.path;
            if (data.fileName.endsWith('.md')) {
                let href = this.$router.resolve({
                    name: 'mdPreview',
                    query: {
                        path: path,
                        name: data.fileName,
                    },
                }).href;
                window.openTrain(href, '_blank');
            } else {
                window.openTrain(`/api/minio/filePreview?path=${path}`);
            }
        },
        // 下载文件
        download(item) {
            let a = document.createElement('a');
            let fileName = item.fileName; //filename名称截取
            a.href = `/api/minio/download?path=${item.path}`;
            a.download = fileName; //命名下载名称
            a.click(); //点击触发下载
        },
    },
};
</script>
<style scoped>
.baseInfo-page {
    --tab-height: 43px;
    --card-height: 400px;
}
.list-wrapper {
    display: flex;
    flex-direction: column;
    /* padding: 10px 16px 0; */
    height: calc(var(--card-height) - var(--tab-height));
    overflow: auto;
    overscroll-behavior: contain;
}
.list-wrapper .cardList {
    flex: auto;
}
.baseInfo-page /deep/ .ivu-tabs-bar {
    margin-bottom: 0;
}
.baseInfo-page /deep/ .ivu-tabs-nav .ivu-tabs-tab {
    padding: 11px 16px;
}
</style>
